/**
 * 
 */
package prv.pursuivant.armory.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import prv.pursuivant.armory.DOMLeecher;
import prv.pursuivant.config.ImporterDesc;

import com.google.inject.Inject;
import com.google.inject.name.Named;

/**
 * @author Kwinto
 * 
 */
public class ArmoryLeecher implements DOMLeecher {

	private final ImporterDesc desc;
	private final String categoryId;

	@Inject
	public ArmoryLeecher(ImporterDesc desc,
			@Named("categoryId") String categoryId) {
		this.desc = desc;
		this.categoryId = categoryId;
	}

	/**
	 * @see prv.pursuivant.armory.DOMLeecher#getDOM(java.lang.String)
	 */
	@Override
	public Document getDOM(String toonName) throws IOException {
		URL url = new URL("http", desc.getRegion() + ".wowarmory.com",
				"/character-achievements.xml?c=" + categoryId + "&r="
						+ URLEncoder.encode(desc.getRealm(), "UTF-8") + "&cn="
						+ URLEncoder.encode(toonName, "UTF-8"));
		return readOnlineDOM(url);
	}

	protected Document readOnlineDOM(URL url) throws IOException {
		// logger.info("Getting url " + url);
		IOException ioe = null;
		int tries = 20;
		while (tries > 0)
			try {
				Document result = singleTryDOM(url);
				return result;
			} catch (IOException e) {
				ioe = e;
				tries--;
				// logger.warning(e.getMessage() + ", tries left: " +
				// tries);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					ioe = new IOException(e1);
				}
			}
		// logger.warning("Document not acquired");
		throw ioe;
	}

	protected Document singleTryDOM(URL url) throws IOException {
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setAllowUserInteraction(false);
		connection.setUseCaches(false);
		connection.setRequestProperty("User-Agent",
				"Mozilla/5.0 Gecko/20070219 Firefox/2.0.0.2");
		connection.setDoOutput(false);
		connection.setConnectTimeout(2000);
		connection.setReadTimeout(2000);
		InputStream stream = connection.getInputStream();
		Document result = null;
		try {
			result = DocumentBuilderFactory.newInstance().newDocumentBuilder()
					.parse(stream);
			if (result.getElementsByTagName("achievement").getLength() < 1)
				throw new IOException("Empty document");
		} catch (IOException e) {
			throw e;
		} catch (RuntimeException e) {
			throw e;
		} catch (Throwable e) {
			throw new IOException(e);
		} finally {
			stream.close();
			connection.disconnect();
		}
		return result;
	}

}
